package com.heima.wemedia.filter;

import com.heima.model.Utils.threadlocal.AppThreadLocalUtils;
import com.heima.model.Utils.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.pojo.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by ZYJ on 2021/5/26 20:12
 */
@WebFilter(filterName = "wmTokenFilter",urlPatterns = "/*")
@Component
@Slf4j
public class WmTokenFilter extends GenericFilter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //得到header中的信息
        String userId =request.getHeader("userId");
        if(userId != null){
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            // 保存到当前线程中
            WmThreadLocalUtils.setUser(wmUser);
        }

        // 如果没有则直接放行
        filterChain.doFilter(request,response);

        //过滤器后置方法 清空登录状态
        AppThreadLocalUtils.clear();
    }
}
